package com.example.myapplication.video.video_sift;

import android.content.Context;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

public class PageLinearLayoutManiger extends LinearLayoutManager implements RecyclerView.OnChildAttachStateChangeListener{
    private PagerSnapHelper pagerSnapHelper;

    public PageLinearLayoutManiger(Context context) {
        super(context);
    }

    @Override
    public void onAttachedToWindow(RecyclerView view) {
        super.onAttachedToWindow(view);
        if (pagerSnapHelper == null) {
            pagerSnapHelper = new PagerSnapHelper();
            pagerSnapHelper.attachToRecyclerView(view);
        }
        view.addOnChildAttachStateChangeListener(this);
    }

    @Override
    public void onScrollStateChanged(int state) {
        super.onScrollStateChanged(state);
        Log.i("ljl", "位置111"+state);

        //滑动接收空闲状态，当前位置就是选中位置
        if (state == RecyclerView.SCROLL_STATE_IDLE) {
            //我去当前对应View
            View view = pagerSnapHelper.findSnapView(this);
            if (onScrollItemListener != null) {
                //获取View对应位置 getPosition(view)
                onScrollItemListener.selected(getPosition(view), getPosition(view) == getItemCount() - 1);
            }
        }
    }

    //释放滑出屏幕 -> AttachToWindow 不在Window绑定


    public void setOnScrollItemListener(OnScrollItemListener onScrollItemListener) {
        this.onScrollItemListener = onScrollItemListener;
    }

    private OnScrollItemListener onScrollItemListener;


    //绑定
    @Override
    public void onChildViewAttachedToWindow(@NonNull View view) {
        if (onScrollItemListener != null && getChildCount() == 1) {
            onScrollItemListener.init(getPosition(view));
        }
    }

    //解绑
    @Override
    public void onChildViewDetachedFromWindow(@NonNull View view) {
        if (onScrollItemListener != null) {
            onScrollItemListener.release(getPosition(view));
        }
    }

    interface OnScrollItemListener {

        void selected(int position, boolean isLoadMore);

        void release(int position);

        void init(int position);
    }


    @Override
    public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) {
        return super.scrollHorizontallyBy(dx, recycler, state);
    }

    @Override
    public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
        return super.scrollVerticallyBy(dy, recycler, state);
    }

    @Override
    public boolean canScrollVertically() {
        return super.canScrollVertically();
    }

    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        super.onLayoutChildren(recycler, state);
    }
}
